TypeScript 中文网: 文档

您所在的位置:网站首页 t ts TypeScript 中文网: 文档

TypeScript 中文网: 文档

2024-06-04 18:08| 来源: 网络整理| 查看: 265

typeof 类型运算符

¥The typeof type operator

JavaScript 已经有一个可以在表达式上下文中使用的 typeof 运算符:

¥JavaScript already has a typeof operator you can use in an expression context:

ts// Prints "string"console.log(typeof "Hello world");Try

TypeScript 添加了一个 typeof 运算符,你可以在类型上下文中使用它来引用变量或属性的类型:

¥TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property:

tslet s = "hello";let n: typeof s; let n: stringTry

这对于基本类型不是很有用,但结合其他类型运算符,你可以使用 typeof 方便地表达许多模式。例如,让我们从查看预定义类型 ReturnType 开始。它接受一个函数类型并产生它的返回类型:

¥This isn’t very useful for basic types, but combined with other type operators, you can use typeof to conveniently express many patterns. For an example, let’s start by looking at the predefined type ReturnType. It takes a function type and produces its return type:

tstype Predicate = (x: unknown) => boolean;type K = ReturnTypePredicate>; type K = booleanTry

如果我们尝试在函数名上使用 ReturnType,我们会看到一个指导性错误:

¥If we try to use ReturnType on a function name, we see an instructive error:

tsfunction f() { return { x: 10, y: 3 };}type P = ReturnType;'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?2749'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?Try

请记住,值和类型不是一回事。要引用值 f 所具有的类型,我们使用 typeof:

¥Remember that values and types aren’t the same thing. To refer to the type that the value f has, we use typeof:

tsfunction f() { return { x: 10, y: 3 };}type P = ReturnType; type P = { x: number; y: number; }Try

限制

¥Limitations

TypeScript 有意限制你可以使用 typeof 的表达式类型。

¥TypeScript intentionally limits the sorts of expressions you can use typeof on.

具体来说,在标识符(即变量名)或其属性上使用 typeof 是唯一合法的。这有助于避免编写你认为正在执行但不是的代码的混乱陷阱:

¥Specifically, it’s only legal to use typeof on identifiers (i.e. variable names) or their properties. This helps avoid the confusing trap of writing code you think is executing, but isn’t:

ts// Meant to use = ReturnTypelet shouldContinue: typeof msgbox("Are you sure you want to continue?");',' expected.1005',' expected.Try


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3